package com.business.dynamic.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.BusinessException;
import com.business.common.exception.CustomException;
import com.business.common.utils.FileUploadUtil;
import com.business.common.utils.PageUtils;
import com.business.dynamic.entity.DynamicMessage;
import com.business.dynamic.entity.vo.DynamicMessageVo;
import com.business.dynamic.mapper.DynamicMessageMapper;
import com.business.dynamic.service.DynamicMessageService;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisKeysUtil;
import com.business.redis.utils.RedisUtil;
import com.business.user.entity.UserDetailsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 动态评论或者赞消息表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-12-02 17:55:03
 * @since 1.0
 */
@Service
public class DynamicMessageServiceImpl implements DynamicMessageService {

    @Autowired
    private DynamicMessageMapper dynamicMessageMapper;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @Override
    @Transactional
    public Integer add(DynamicMessage dynamicMessage) {
        if (dynamicMessage.getUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (dynamicMessage.getFromUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "fromUserId");
        }
        if (dynamicMessage.getDynamicId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "dynamicId");
        }
        if (dynamicMessage.getItemId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "itemId");
        }
        dynamicMessage.setCreateTime(new Date());
        Set<String> keys = new HashSet<>();
        String countByTypeKey = String.format(RedisKeyConstant.DYNAMIC_MESSAGE_COUNT_BY_TYPE, dynamicMessage.getUserId());
        String countKey = String.format(RedisKeyConstant.DYNAMIC_MESSAGE_COUNT, dynamicMessage.getUserId());
        keys.add(countByTypeKey);
        keys.add(countKey);

        RedisUtil.delValue(keys);
        return dynamicMessageMapper.insert(dynamicMessage);
    }

    @Override
    @Transactional
    public Integer updateAll(Integer userId, Integer type) {
        DynamicMessage d = new DynamicMessage();
        d.setIsRead(1);
        Integer result = dynamicMessageMapper.update(d, new EntityWrapper<DynamicMessage>().eq("user_id", userId).eq("type", type).eq("is_read", 0));
        if (result > 0) {
            return result;
        } else {
            throw new BusinessException(BusinessExceptionEnum.MESSAGE_UPDATE_ERROR);
        }

    }

    @Override
    public PageUtils queryPage(Page<DynamicMessage> page, Integer userId, Integer type, Integer isAll) {
        if (type == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "type");
        }
        Wrapper<DynamicMessage> wrapper = new EntityWrapper<>();
        wrapper.eq("dm.user_id", userId);
        if (isAll == null || isAll == 0) {
            wrapper.eq("dm.is_read", 0);
        }
        page.setOptimizeCount(true);
        List<DynamicMessageVo> result = null;
        if (type == 0) {
            wrapper.eq("dm.type", 0);
            page.setSearchCount(false);
            page.setTotal(dynamicMessageMapper.getCount(wrapper));
            wrapper.orderBy("dm.create_time", false).orderBy("dm.is_read", false);
            result = dynamicMessageMapper.queryCommentMessagePage(page, wrapper);
        } else {
            wrapper.eq("dm.type", 1);
            page.setSearchCount(false);
            page.setTotal(dynamicMessageMapper.getCount(wrapper));
            wrapper.orderBy("dm.create_time", false);
            result = dynamicMessageMapper.queryLikeMessagePage(page, wrapper);
        }
        result.forEach(dynamicMessageVo -> {
           if(dynamicMessageVo.getDynamicBigImage() != null){
               dynamicMessageVo.setDynamicBigImage(fileUploadUtil.getUrl(dynamicMessageVo.getDynamicBigImage()));
           }
        });
        Set<Integer> ids = new HashSet<>();
        result.forEach(dynamicMessageVo -> {
            if (dynamicMessageVo.getFromUserId() != null) {
                ids.add(dynamicMessageVo.getFromUserId());
            }
        });
        //获取用户信息
        Map<Integer, UserDetailsDto> nameMap = userService.getUserNameList(ids);
        result.forEach(dynamicMessageVo -> {
            UserDetailsDto userDto = nameMap.get(dynamicMessageVo.getFromUserId());
            if (userDto != null) {
                dynamicMessageVo.setFromUserRealName(userDto.getRealName());
                dynamicMessageVo.setFromUserHeadUrl(userDto.getHeadUrl());
            } else {
                dynamicMessageVo.setFromUserRealName("未设置");
            }
        });
        PageUtils pageUtils = new PageUtils(result, page.getTotal());
        return pageUtils;
    }


    @Override
    public Integer getCount(Integer userId) {
        Integer count = dynamicMessageMapper.selectCount(new EntityWrapper<DynamicMessage>().eq("user_id", userId).eq("is_read", 0));
        return count;
    }

    @Override
    public List<Map<String, Integer>> getCountByType(Integer userId) {
        List<Map<String, Integer>> resultMap = dynamicMessageMapper.getCountByType(userId);
        return resultMap;
    }

    @Override
    @Transactional
    public Integer delete(Integer itemId, Integer type) {
        return dynamicMessageMapper.delete(new EntityWrapper<DynamicMessage>().eq("item_id", itemId).eq("type", type));
    }


}